#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include <cerrno>
#include <cstdlib>
#include <ctime>

#define FIFO_FILE "chat_fifo"

int main() {
    int fd = open(FIFO_FILE, O_RDWR);
    time_t rawTime;
    struct tm* localTime;
    char timeString[128];
    char message[1024];
    while (1) {
        printf("Client:");
        fgets(message, sizeof(message), stdin);
        write(fd, message, strlen(message) + 1);
        if (strcmp(message, "exit\n") == 0) break;
        sleep(2);

        read(fd, message, sizeof(message));
        time(&rawTime);
        localTime = localtime(&rawTime);
        strftime(timeString, sizeof(timeString), "%H:%M:%S", localTime);
        printf("[%s Server]: %s\n", timeString, message);
        if (strcmp(message, "exit\n") == 0) break;
    }
    close(fd);
    return 0;
}
